package com.ruiysoft.controller.aftersaleconf;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruiysoft.controller.aftersaleconf.vo.AftersaleConfVo;
import com.ruiysoft.entity.aftersaleconf.AftersaleConf;
import com.ruiysoft.entity.aftersaleconf.AftersaleConfSpuRela;
import com.ruiysoft.entity.mdse.MerchandiseSpu;
import com.ruiysoft.entity.sys.SysMicroShop;
import com.ruiysoft.pub.core.Result;
import com.ruiysoft.pub.core.ResultGenerator;
import com.ruiysoft.service.aftersaleconf.IAftersaleConfService;
import com.ruiysoft.service.aftersaleconf.IAftersaleConfSpuRelaService;
import com.ruiysoft.service.mdse.IMerchandiseSpuService;
import com.ruiysoft.service.sys.clent.LoginContextUtil;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2018-11-24T21:35:29.769+08:00")

@RestController
public class AftersaleConfApiController implements AftersaleConfApi {

    private static final Logger log = LoggerFactory.getLogger(AftersaleConfApiController.class);

    private final IAftersaleConfSpuRelaService spuRelaService;
    private final IAftersaleConfService confService;
    private final IMerchandiseSpuService spuService;
    private final InnrAftersaleConfApi innrAftersaleConfApi;
    @org.springframework.beans.factory.annotation.Autowired
    public AftersaleConfApiController(IAftersaleConfSpuRelaService spuRelaService, IAftersaleConfService confService, IMerchandiseSpuService spuService, InnrAftersaleConfApi innrAftersaleConfApi) {
        this.spuRelaService = spuRelaService;
        this.confService = confService;
        this.spuService = spuService;
        this.innrAftersaleConfApi = innrAftersaleConfApi;
    }
    private Long getShopId() {
        SysMicroShop shop = LoginContextUtil.instance().getEntryMicroShop();
        return shop.getId();
    }

    @Override
    public Result<AftersaleConfVo> aftersaleConfBySkuIdSkuIdGet(@ApiParam(value = "",required=true) @PathVariable("skuId") Long skuId) {
        try {
            List<Long> skuIdList = new ArrayList<>();
            skuIdList.add(skuId);
            Result<Map<Long, AftersaleConfVo>> result = innrAftersaleConfApi.innrAftersaleConfGetConfPost(skuIdList);
            if(result!=null&&result.isSuccess()){
                return ResultGenerator.genSuccessResult(result.getData().get(skuId));
            }else{
                return ResultGenerator.genSuccessResult(new AftersaleConfVo().returnedDay(7).exchangeDay(15));
            }
        } catch (Exception e) {
            log.error("skuid查询退换货规则--{}",skuId, e);
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }
    @Override
    public Result<AftersaleConfVo> aftersaleConfBySpuIdSpuIdPost(@ApiParam(value = "spuId",required=true) @PathVariable("spuId") Long spuId) {
        try {
            List<Long> spuIdList = new ArrayList<>();
            spuIdList.add(spuId);
            Result<Map<Long, AftersaleConfVo>> result = innrAftersaleConfApi.innrAftersaleConfGetConfBySpuIdPost(spuIdList);
            if(result!=null&&result.isSuccess()){
                return ResultGenerator.genSuccessResult(result.getData().get(spuId));
            }else{
                return ResultGenerator.genSuccessResult(new AftersaleConfVo().returnedDay(7).exchangeDay(15));
            }
        } catch (Exception e) {
            log.error("spuid查询退换货规则--{}",spuId, e);
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }
    @Override
    public Result<Void> aftersaleConfDefIdGet(@ApiParam(value = "",required=true) @PathVariable("id") Long id) {
        Long shopId = getShopId();
        try {
            confService.setDefByid(id,shopId);
            return ResultGenerator.genSuccessResult();
        } catch (Exception e) {
            log.error("商铺设置默认退换货设置模板--{}--{}",shopId,id, e);
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

    @Override
    public Result<Void> aftersaleConfDelIdTypeGet(@ApiParam(value = "",required=true) @PathVariable("id") Long id, @ApiParam(value = "（1，普通删除，2，强制删除）",required=true) @PathVariable("type") Integer type) {
        Long shopId = getShopId();
        //校验修改时店铺id是否一致
        AftersaleConf aftersaleConf = confService.getById(id);
        if(aftersaleConf!=null&&!Objects.equals(aftersaleConf.getShopId(),shopId)){
            throw new IllegalArgumentException("登录店铺不是此规则所属店铺");
        }
        if(aftersaleConf !=null && aftersaleConf.getDefault() != null && aftersaleConf.getDefault()){
            throw new IllegalArgumentException("该规则是店铺默认规则不能删除");
        }
        if(type!=2){
            int count = spuRelaService.count(new QueryWrapper<AftersaleConfSpuRela>().eq("aftersale_conf_id",id));

            if(count>0){
                throw new IllegalArgumentException("存在已绑定该规则的spu！");
            }
        }else {
            spuRelaService.remove(new QueryWrapper<AftersaleConfSpuRela>().eq("aftersale_conf_id",id));
        }
        confService.removeById(id);
        return ResultGenerator.genSuccessResult();
    }

    @Override
    public Result<AftersaleConfVo> aftersaleConfIdGet(@ApiParam(value = "",required=true) @PathVariable("id") Long id) {
        Long shopId = getShopId();
        try {
            AftersaleConf aftersaleConf = confService.getById(id);
            return ResultGenerator.genSuccessResult(
                    new AftersaleConfVo().id(aftersaleConf.getId()).name(aftersaleConf!=null?(aftersaleConf.getName()!=null?aftersaleConf.getName():""):"")
                            .exchangeDay(aftersaleConf!=null?(aftersaleConf.getExchangeDay()!=null?aftersaleConf.getExchangeDay():0):0)
                            .returnedDay(aftersaleConf!=null?(aftersaleConf.getReturnedDay()!=null?aftersaleConf.getReturnedDay():0):0)
                            .isDefault(aftersaleConf!=null?(aftersaleConf.getDefault()!=null?aftersaleConf.getDefault():false):false));
        } catch (Exception e) {
            log.error("商铺查询退换货设置模板--{}--{}",shopId,id, e);
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

    @Override
    public Result<List<AftersaleConfVo>> aftersaleConfListGet() {
        Long shopId = getShopId();
        try {
            List<AftersaleConf> list = confService.list(new QueryWrapper<AftersaleConf>().eq("shop_id",shopId));
            return ResultGenerator.genSuccessResult(list.stream().map(aftersaleConf->new AftersaleConfVo().id(aftersaleConf.getId())
                    .name(aftersaleConf!=null?(aftersaleConf.getName()!=null?aftersaleConf.getName():""):"")
                    .exchangeDay(aftersaleConf!=null?(aftersaleConf.getExchangeDay()!=null?aftersaleConf.getExchangeDay():0):0)
                    .returnedDay(aftersaleConf!=null?(aftersaleConf.getReturnedDay()!=null?aftersaleConf.getReturnedDay():0):0)
                    .isDefault(aftersaleConf!=null?(aftersaleConf.getDefault()!=null?aftersaleConf.getDefault():false):false)).collect(Collectors.toList()));
        } catch (Exception e) {
            log.error("商铺查询退换货设置模板list--{}",shopId, e);
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

    @Override
    public Result<Void> aftersaleConfSavePost(@ApiParam(value = ""  )  @Valid @RequestBody AftersaleConfVo body) {
        Long shopId = getShopId();
        try {
            //校验修改时店铺id是否一致
            if(body.getId()!=null){
                AftersaleConf aftersaleConf = confService.getById(body.getId());
                if(aftersaleConf!=null&&!Objects.equals(aftersaleConf.getShopId(),shopId)){
                    throw new IllegalArgumentException("登录店铺不是此规则所属店铺");
                }
            }
            AftersaleConf aftersaleConf = new AftersaleConf().setName(body.getName()).setId(body.getId()).setShopId(shopId).setDefault(body.isIsDefault()).setExchangeDay(body.getExchangeDay()).setReturnedDay(body.getReturnedDay());
            confService.saveAftersaleConf(aftersaleConf,shopId);
            return ResultGenerator.genSuccessResult();
        } catch (Exception e) {
            log.error("商铺保存退换货设置模板--{}--{}",shopId,JSON.toJSONString(body), e);
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

    @Override
    public Result<Void> aftersaleConfSetSpuRelaConfIdPost(@ApiParam(value = "confId",required=true) @PathVariable("confId") Long confId, @ApiParam(value = "" ,required=true )  @Valid @RequestBody List<Long> spuIds) {
        Long shopId = getShopId();
        try {
            //校验修改时店铺id是否一致
            AftersaleConf aftersaleConf = confService.getById(confId);
            if(aftersaleConf!=null&&!Objects.equals(aftersaleConf.getShopId(),shopId)){
                throw new Exception("登录店铺不是此规则所属店铺");
            }
            int count = spuService.count(new QueryWrapper<MerchandiseSpu>().in("spu_id",spuIds));
            if(!Objects.equals(count,spuIds.size())){
                throw new Exception("存在不在本店铺的spuid");
            }
            List<AftersaleConfSpuRela> spuRelas = spuIds.stream().filter(Objects::nonNull).map(spuId->new AftersaleConfSpuRela().setAftersaleConfId(confId).setShopId(shopId).setSpuId(spuId)).collect(Collectors.toList());
            spuRelaService.saveOrUpdateBatch(spuRelas);
            return ResultGenerator.genSuccessResult();
        } catch (Exception e) {
            log.error("商铺spu设置退换货模板--{}--{}--{}",shopId,confId,JSON.toJSONString(spuIds), e);
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

}
